<template>
    <div class="template">
        <div class="temMain">
            <div class="tip1">
                <img :src="ThisWeek" style="width: 148px;" />
                <div class="topInfo">
                    <van-badge :content="badgeNum" color="#2EAC7F" :show-zero="false">
                        <img :src="home_collect_button" style="width: 38px;height: 38px;" @click="router.push('/myRecipes')"/>
                    </van-badge>
                    <div style="width: 95px;height: 38px;margin-left: 10px;position: relative;" @click="router.push('/store')">
                        <img :src="home_store_button" style="width: 100%;height: 38px;"/>
                        <!-- <div class="coinsNum">{{ coinsNum > 99? '99+' : coinsNum }}</div> -->
                        <div class="coinsNum">Store</div>
                    </div>
                </div>
            </div>
            <div class="planTop">
                <div>Ready to plan this week?</div>
                <div class="chooseWeek">
                    <div class="blockItem" :style="{marginLeft: index == 4 ? '25px' : '0', marginRight: index == 6 ? '25px' :'0'}" v-for="(item, index) in 7" :key="index" @click="changeStatus(index)">
                        <img v-if="weekType[index] == 1" :src="week_active[index]" style="width: 100%;height: 100%;"/>
                        <img v-else :src="week[index]" style="width: 100%;height: 100%;"/>
                    </div>
                </div>
            </div>
            <div class="weekList">
                <div v-for="(item, index) in weekType" :key="index">
                    <div v-if="item == 1" class="weekName">
                        {{ weekPlan[index].name }}
                        <van-popover v-model:show="showPopover[index]" placement="bottom-end">
                            <van-grid square clickable :border="true" column-num="1" >
                                <van-grid-item @click="checkXX(0, index)">
                                    <div style="height: 40px;display: flex;align-items: center;width: 140px;justify-content: center;">
                                        <img :src="mealplan_addsavedrecipe" style="width: 130px;" />
                                    </div>
                                </van-grid-item>
                                <van-grid-item @click="checkXX(1, index)">
                                    <div style="height: 40px;display: flex;align-items: center;width: 140px;justify-content: center;">
                                        <img :src="mealplan_createnewrecipe" style="width: 130px;" />
                                    </div>
                                </van-grid-item>
                            </van-grid>
                          <template #reference>
                            <img :src="mealplan_add_button" style="height: 34px;" />
                          </template>
                        </van-popover>
                    </div>
                    <div v-if="item == 1 &&  weekPlan[index].plan.length > 0" class="weekCon">
                        <div v-for="(item2, index2) in weekPlan[index].plan" :key="index2" class="imgBlock newBlock">
                            <img style="width: 100%;height: 100%;" :src="item2.img" v-if="item2.type == 1" />
                            <img style="width: 100%;height: 100%;" :src="recipesList[item2.index]" v-else />
                            <div class="close" @click="delItem(index, index2)">
                                <img :src="close" style="width: 14px;"/>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <van-popup v-model:show="show" style="background-color: transparent;">
        <div class="addItem">                        
            <img :src="close3" class="close2" @click="show = false"/>
            <div class="showall">
                <div v-for="(item, index) in planList" :key="index">
                    <img class="imgBlock" :src="item.img" v-if="item.type == 1" @click="addInfo(index)"/>
                    <img class="imgBlock" :src="recipesList[item.index]" v-else @click="addInfo(index)"/>
                </div>
            </div>
        </div>
    </van-popup>

    <MeanBar />
</template>
<script setup>
import { showConfirmDialog, showToast } from 'vant';
import MeanBar from '../component/MeanBar.vue'
import ThisWeek from '../assets/ThisWeek.png'
import close from '../assets/close.png'
import close3 from '../assets/close3.png'
import home_collect_button from '../assets/home_collect_button.png'
import home_store_button from '../assets/home_store_button.png'
import mealplan_add_button from '../assets/mealplan_add_button.png'
import mealplan_addsavedrecipe from '../assets/mealplan_addsavedrecipe.png'
import mealplan_createnewrecipe from '../assets/mealplan_createnewrecipe.png'
import recipes1 from '../assets/recipesImg/recipes1.png'
import recipes2 from '../assets/recipesImg/recipes2.png'
import recipes3 from '../assets/recipesImg/recipes3.png'
import recipes4 from '../assets/recipesImg/recipes4.png'
import recipes5 from '../assets/recipesImg/recipes5.png'
import recipes6 from '../assets/recipesImg/recipes6.png'
const recipesList = [recipes1, recipes2, recipes3, recipes4, recipes5, recipes6]
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router';
import M from '../assets/M.png'
import M_active from '../assets/M_active.png'
import T from '../assets/T.png'
import T_active from '../assets/T_active.png'
import W from '../assets/W.png'
import W_active from '../assets/W_active.png'
import F from '../assets/F.png'
import F_active from '../assets/F_active.png'
import S from '../assets/S.png'
import S_active from '../assets/S_active.png'
let week = [M, T, W, T, F, S, S]
let week_active = [M_active, T_active, W_active, T_active, F_active, S_active, S_active]
const weekType = ref([])
const weekPlan = ref([])
const router = useRouter()
const badgeNum = ref(0)
const planList = ref([])
const getNum = () => {
    let recipeList = localStorage.getItem('recipeList') ? JSON.parse(localStorage.getItem('recipeList')) : []
    let num1 = recipeList.length
    let recipeXT =  JSON.parse(localStorage.getItem('recipeXT'))
    let num2 = recipeXT.filter(item => item.collect == 1).length
    badgeNum.value = num1 + num2

    let list1 = recipeList.map((item, index) => ({type: 1, img: item.img, index, name: item.name}))
    let list2 = recipeXT.map((item, index) => ({type: 0, index}))
    planList.value = [...list1, ...list2]
}
const coinsNum = ref(0)
onMounted(() => {
    coinsNum.value = localStorage.getItem('CPCoinsNum') ? Number(localStorage.getItem('CPCoinsNum')) : 0
    getNum()
    weekType.value = JSON.parse(localStorage.getItem("weekType"))
    if (!localStorage.getItem('weekPlan')) {
        localStorage.setItem('weekPlan', JSON.stringify([{name: 'Monday', plan: []},{name: 'Tuesday', plan: []},{name: 'Wednesday', plan: []},{name: 'Thursday', plan: []},{name: 'Friday', plan: []},{name: 'Saturday', plan: []},{name: 'Sunday', plan: []}]))
    }

    let nameList = localStorage.getItem('recipeList') ? JSON.parse(localStorage.getItem('recipeList')).map(item => item.name) : []
    console.log(JSON.parse(localStorage.getItem('weekPlan')));
    isDelete(JSON.parse(localStorage.getItem('weekPlan')), nameList)
    weekPlan.value = JSON.parse(localStorage.getItem('weekPlan'))
})
const changeStatus = (index) => {
    let data = weekType.value
    let val = weekType.value[index] == 0 ? 1 : 0
    data[index] = val
    localStorage.setItem('weekType', JSON.stringify(data))
    if (val == 0) {
        weekPlan.value[index].plan = []
        localStorage.setItem('weekPlan', JSON.stringify(weekPlan.value))
    }
}
const showPopover = ref([false,false,false,false,false,false,false]);
const addId = ref(-1)
const show = ref(false)
const checkXX = (type, index) => {
    showPopover.value[index] = false
    if (type == 1) {
        router.push('/createRecipes')
    }else {
        addId.value =index
        show.value = true
    }
}
const addInfo = (index) => {
    if (isObjectInArray(weekPlan.value[addId.value].plan, planList.value[index])) {
        showToast('Can only be added once')
        return
    }
    showConfirmDialog({
      message: 'Adding dishes costs 10 coins',
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel'
    }).then(() => {

        if (coinsNum.value < 10) {
            showToast('Not enough coins')
            return
        }else {
            try {
                let data = JSON.parse(JSON.stringify(weekPlan.value))
                data[addId.value].plan.push(planList.value[index])
                localStorage.setItem('weekPlan', JSON.stringify(data))
                show.value = false
                coinsNum.value = coinsNum.value - 10
                localStorage.setItem('CPCoinsNum', coinsNum.value)
                weekPlan.value = data
            } catch {
                showToast('Insufficient memory, please delete some recipes you added')
            }

        }

    })


}
const delItem = (index, index2) => {
    showConfirmDialog({
          message: 'Are you sure you want to delete it?',
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel'
        }).then(() => {
            weekPlan.value[index].plan.splice(index2, 1)
            localStorage.setItem('weekPlan', JSON.stringify(weekPlan.value))
        })
}
const isObjectInArray = (array, object) => {
    return array.some(item => item.type === object.type && item.index === object.index);
}
const isDelete = (array, nameList) => {
    let willdel = []
    array.forEach((item, index) => {
        item.plan.forEach((item2, index2) => {
            if (item2.type == 1 && nameList.indexOf(item2.name) == -1) {
                willdel.push([index, index2])
            }
        })
    })
    if (willdel.length <= 0) return
    willdel.forEach((item, index) => {
        array[item[0]].plan.splice(item[1], 1)
    })
    localStorage.setItem('weekPlan', JSON.stringify(array))
}
</script>
<style scoped>
.tip1 {
    margin-top: 40px;
    width: 100%;
    font-weight: 500;
    font-size: 14px;
    color: #737373;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.topInfo {
    display: flex;
}
.coinsNum {
    position: absolute;
    top: 50%;
    /* left: 46px; */
    right: 8px;
    /* right: 5px; */
    transform: translateY(-50%);
    color: #fff;
    font-size: 13px;
}
.planTop {
    width: 100%;
    height: 25vh;
    background: #80D9B9;
    border-radius: 0px 0px 0px 0px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-weight: bold;
    font-size: 20px;
    color: #161616;
    padding-top: 15px;
    box-sizing: border-box;
}
.chooseWeek {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    width: 67%;
    margin-top: 20px;
}
.blockItem {
    width: 45px;
    height: 45px;
    margin-bottom: 10px;
}
.weekList {
    width: 100%;
    box-sizing: border-box;
    height: 45vh;
    overflow: auto;
}
.weekName {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 70px;
    border-bottom: 1px solid #D9D9D9;
    font-weight: bold;
    font-size: 20px;
    color: #707576;
}
.addItem {
    width: 70vw;
    height: 40vh;
    background-color: #fff;
    border-radius: 10px;
    overflow: hidden;
}
.close {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 21px;
    height: 21px;
    background: #472A2A;
    opacity: 0.8;
    border-radius: 21px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.close2 {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 22px;
    height: 22px;
    border-radius: 21px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.showall {
    width: 100%;
    height: 80%;
    margin-top: 40px;
    overflow: auto;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0 20px;
    box-sizing: border-box;
}
.imgBlock {
    width: 100px;
    height: 100px;
    border-radius: 10px;
    margin-bottom: 10px;
    overflow: hidden;
    position: relative;
}
.weekCon {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}
.newBlock {
    width: 150px;
    height: 150px;
}
</style>